<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/11/7
 * Time: 下午7:28
 */

namespace app\mobile\controller;

use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\WxUser;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Pay extends Controller
{
    public function pay()
    {   $request=request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant=new Merchant();
        $Agent=new Agent();
        $System=new System();
        $WxOpen=new WxOpen();
        $user = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $user['agent']))->find();
        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'component_token' => $agent['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $agent['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("wxpay/pay", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

                session('openid', $openid);
            }
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->get_user_info($openid, $request->param('id'));
        $this->assign("headimg", $user['img']);
        $this->assign('shmc', $user['merchant']);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        return $this->fetch();

    }

    public function pay2()
    {
        $request=request()->param();
        $Paylog=new Paylog();
        $norderid =$Paylog->where(array('orderid' => request()->post('orderid')))->count('id');
        if ($norderid != 0) {
            echo 1;
        } else {
            $Merchant=new Merchant();
            $Agent=new Agent();
            $WxOpen=new WxOpen();
            $map['id'] =$request['id'];
            $config =$Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $price = request()->post('price');
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no =request()->post('orderid');
            $body = "快捷支付";
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $total_fee = $price * 100;
            $data['orderid'] = $out_trade_no;
            $data['mid'] = request()->param('id');
            $data['openid'] =request()->post('openid');
            $data['pay_statu'] = 0;
            $data['price'] = $price;
            $data['add_time'] = time();
            $Paylog=new Paylog();
            $add = $Paylog->save($data);
            $openid = request()->post('openid');
            $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
            $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
            $nonce_str = $weObj->generateNonceStr();
            $pay_xml = $weObj->createPackageXml($appid,$sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, $openid);
            $pay_xml = $weObj->get_pay_id($pay_xml);
            $prepay_id = $pay_xml['prepay_id'];
            $jsApiObj["appId"] = $appid;
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $nonce_str;
            $jsApiObj["package"] = "prepay_id=" . $prepay_id;
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
            return json($jsApiObj);
        }
    }

    function payover()
    {
        $request= request();
        $Merchant=new Merchant();
        $Agent=new Agent();
        $WxOpen=new WxOpen();
        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $request->param('orderid');
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid =$userwx['authorizer_appid'];
        $pay_xml = $weObj->createOrderXml($appid, $mch_id,$sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayNum($pay_xml);
        $orderno = $payorder_xml['transaction_id'];
        $pay_zt = $payorder_xml['trade_state'];
        if ($pay_zt == "SUCCESS") {
            $data = 0;
        } else {
            $data = 1;
        }
        echo $data;
    }


    public function orderinfo()
    {
        $request=request();
        $Merchant=new Merchant();
        $Agent=new Agent();
        $WxOpen=new WxOpen();
        $System=new System();
        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $config2 = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $config2['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config2['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config2['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config2['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config2['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $weObj = new Wxobjopen($options);
        $openid = session('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Wxpay/orderinfo", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');
                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
            }
        }
        $maq['orderid'] = $request->param('orderid');
        $Paylog=new Paylog();
        $order = $Paylog->where($maq)->find();
        if ($openid == $order['openid']) {
            $mav['id'] = $request->param('id');
            $Merchant=new Merchant();
            $shmc = $Merchant->where($mav)->value('merchant');
            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->assign('jssdk', $jssdk);
        return $this->fetch('index/orderinfo');
    }

    public function get_user_info($openid = 'ok2ajuAJm7owX6UaYGoQZ05YFcww', $id = 1)
    {
        $us['openid'] = $openid;
        $Wxuser=new WxUser();
        $user = $Wxuser->where("openid='$openid'")->count('id');
        if ($user == 0) {
            $map['id'] = $id;
            $Merchant=new Merchant();
            $Agent=new Agent();
            $WxOpen=new WxOpen();
            $System=new System();
            $user = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $user['agent']))->find();
            $config = $System->where(array('id' => 1))->find();
            $users =$WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options = array(
                'component_token' => $config['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $config['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            );
            $weObj = new Wxobjopen ($options);
            $userinfo = $weObj->getUserInfo($openid);
            $userinfo = json_encode($userinfo);
            $data['openid'] = $openid;
            $data['wx_info'] = $userinfo;
            $data['addtime'] = time();
            $add = $Wxuser->save($data);
        }
    }
    
    public function getorder2()
    {
        $request=request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }
}